What are the benefits of `while(condition) { //work }` and `do { //work } while(condition)`?

Posted by Shaharyar on Stack Overflow See other posts from Stack Overflow or by Shaharyar
Published on 2010-05-31T18:12:54Z Indexed on 2010/05/31 18:23 UTC
Read the original article Hit count: 223

I found myself confronted with an interview question where the goal was to write a sorting algorithm that sorts an array of unsorted int values:

int[] unsortedArray = { 9, 6, 3, 1, 5, 8, 4, 2, 7, 0 };

Now I googled and found out that there are so many sorting algorithms out there! Finally I could motivate myself to dig into Bubble Sort because it seemed pretty simple to start with.

I read the sample code and came to a solution looking like this:

    static int[] BubbleSort(ref int[] array)
    {
        long lastItemLocation = array.Length - 1;
        int temp;
        bool swapped;

        do
        {
            swapped = false;
            for (int itemLocationCounter = 0; itemLocationCounter < lastItemLocation; itemLocationCounter++)
            {
                if (array[itemLocationCounter] > array[itemLocationCounter + 1])
                {
                    temp = array[itemLocationCounter];
                    array[itemLocationCounter] = array[itemLocationCounter + 1];
                    array[itemLocationCounter + 1] = temp;

                    swapped = true;
                }
            }

        } while (swapped);

        return array;
    }

I clearly see that this is a situation where the do { //work } while(cond) statement is a great help to be and prevents the use of another helper variable.

But is this the only case that this is more useful or do you know any other application where this condition has been used?

© Stack Overflow or respective owner

Related posts about programming-languages

Related posts about c#4.0